import Router from '@koa/router';
import db from '../mysqlHelper.js';
import response from '../response.js';
import axios from 'axios';

const router = new Router;
router.prefix('/api');




//根据项目配置获取萤石云配置
async function   getysConfig(project_id){
    let res = await db.findOne('project_cfg',{id:project_id});
    if(res==null){
        console.error(`项目${project_id}配置不存在`);
        return null;
    }
    return res.cfg;
}
/*
*获取直播地址
* @param {*} token 萤石云token
* @param {*} deviceSerial 设备序列号
* @param {*} protocol 流播放协议，1-ezopen、2-hls、3-rtmp、4-flv，默认为1
* @param {*} type 播放地址的类型，1-预览，2-本地录像回放，3-云存储录像回放，非必选，默认为1；回放仅支持rtmp、ezopen、flv协议
* @param {*} quality 视频清晰度，1-高清（主码流）、2-流畅（子码流）
* @param {*} startTime 本地录像/云存储录像回放开始时间,云存储开始结束时间必须在同一天，示例：2019-12-01 00:00:00
* @param {*} stopTime 本地录像/云存储录像回放结束时间,云存储开始结束时间必须在同一天，示例：2019-12-01 23:59:59
* @returns 
*/
async function getUrl(token, deviceSerial,protocol=4,type=1,quality=1,startTime="",stopTime="") {
    try {
        let url = `https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${token}&deviceSerial=${deviceSerial}&protocol=${protocol}&type=${type}&quality=${quality}`;
        if (startTime != "" && stopTime != "") {
            url += `&startTime=${startTime}&stopTime=${stopTime}`;
        }
        console.log(url);
       let  res = await axios.post(url)
        if (res.data.code == 200) {
            return{code:1,data:{url:res.data.data.url,expireTime:res.data.data.expireTime}};
        }
        else {
            return { code: 0, msg: JSON.stringify(res.data) };
        }
    }
    catch (error) {
        console.log({ code: '500', msg: `${error.message}` });
        return { code: 0, msg: error.message };
    }
}

async function getToken(AppKey,Secret) {
    try {
        let res = await axios.post(`https://open.ys7.com/api/lapp/token/get?appKey=${AppKey}&appSecret=${Secret}`);
        if (res.data.code == 200) {
            return { code: 1, token: res.data.data.accessToken };
        }
        else {
            return { code: 0, msg: JSON.stringify(res.data) };
        }
    } catch (error) {
        return { code: 0, msg: error.message };
    }

}

router.post('/camera/getUrl', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.cameraSerial == null) {
        ctx.body = response.fail("缺少必填字段 cameraSerial");
        return;
    }
    if (body.project_id == null) {
        ctx.body = response.fail("缺少必填字段 project_id");
        return;
    }
    let ys_config = await getysConfig(body.project_id);
    if (ys_config == null) {
        ctx.body = response.fail("项目配置不存在");
        return;
    }
    if(ys_config.appKey==null){
        ctx.body = response.fail("项目配置appKey不存在");
        return;
    }
    if(ys_config.appSecret==null){
        ctx.body = response.fail("项目配置appSecret不存在");
        return;
    }
    console.log(ys_config);
    let res = await getToken(ys_config.appKey,ys_config.appSecret);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    if(body.protocol==null){
        body.protocol=4;
    }
    if(body.type==null){
        body.type=1;
    }
    if(body.quality==null){
        body.quality=1;
    }   
    if(body.startTime==null){
        body.startTime="";
    }
    if(body.stopTime==null){
        body.stopTime="";
    }
    let token = res.token;
    res = await getUrl(token, body.cameraSerial,body.protocol,body.type,body.quality,body.startTime,body.stopTime);
    if(res.code==0){
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res);

});







export { router };